package com.jumi.microservice.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.core.web.page.TableDataInfo;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.dto.reponse.RealNameReponse;
import com.jumi.microservice.dto.request.RealNameQueryRequest;
import com.jumi.microservice.dto.request.RealNameUpdateRequest;
import com.jumi.microservice.entity.JmRealnameAuthentication;
import com.jumi.microservice.entity.JmRealnameAuthenticationLog;
import com.jumi.microservice.entity.JmUser;
import com.jumi.microservice.enums.CheckStatus;
import com.jumi.microservice.service.IJmRealnameAuthenticationLogService;
import com.jumi.microservice.service.IJmRealnameAuthenticationService;
import com.jumi.microservice.service.IJmUserService;
import com.jumi.microservice.service.PageService;
import com.jumi.microservice.util.WrapperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户实名认证表 前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-08-03
 */
@RestController
@RequestMapping("/jm-realname-authentication")
@Api(value = "用户实名认证", tags = {"用户实名认证接口"})
public class JmRealnameAuthenticationController {

    @Resource
    IJmRealnameAuthenticationService service;

    @Resource
    IJmRealnameAuthenticationLogService logService;

    @Resource
    IJmUserService userService;

    @Resource
    IJmRealnameAuthenticationService realNameService;

    @PostMapping("/getInfo")
    @ApiOperation("用户实名认证分页数据")
    public TableDataInfo<RealNameReponse> getInfo(RealNameQueryRequest request,
                                                  Integer size, Integer current) {

        Page page = new Page(current, size);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, request);
        wrapper.orderByDesc("create_time");
        page = service.getPage(page, wrapper);
        return PageService.getDataTableInfo(page);
    }

    @PostMapping("/update")
    @ApiOperation("用户实名认证驳回/审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authId",value = "申请记录ID",required = true),
            @ApiImplicitParam(name = "remark",value="审核原因"),
            @ApiImplicitParam(name = "status",value = "审核状态;待审核(0),已通过(1),未通过(2),未申请(3)",required = true)
    })
    @Transactional
    public ResponseResult update(Integer authId, CheckStatus status, String remark) {
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();

        JmRealnameAuthentication auth = service.getById(authId);
        if (ObjectUtil.isNull(auth)) return ResponseResult.error("未查询到相关记录!");
        CheckStatus checkStatus = auth.getStatus();//审核状态
        if (checkStatus.equals(CheckStatus.未通过)) {
            return ResponseResult.error("未通过记录，不允许操作!");
        }
        auth.setStatus(status);

        auth.setUpdateTime(LocalDateTime.now());
        auth.setExamineTime(LocalDateTime.now());
        auth.setRemark(remark);
        auth.setAdminId(adminId);
        auth.setAdminName(adminName);

        // 实名认证通过后,更新user表实名认证字段状态
        if(status.equals(CheckStatus.已通过)){
            UpdateWrapper wrapper=new UpdateWrapper();
            wrapper.set("is_realname_authentication",1);
            wrapper.eq("id",auth.getUid());
            userService.update(wrapper);
        }

        if(status.equals(CheckStatus.未通过)){
            UpdateWrapper wrapper=new UpdateWrapper();
            wrapper.set("is_realname_authentication",0);
            wrapper.eq("id",auth.getUid());
            userService.update(wrapper);
        }

        return ResponseResult.success(service.update(auth));
    }


    @PostMapping("/batchUpdate")
    @ApiOperation("用户实名认证批量驳回/审核")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "ids",name = "申请记录ID集合",required = true),
            @ApiImplicitParam(value = "remark",name="审核原因"),
            @ApiImplicitParam(value = "status",name = "审核状态;待审核(0),已通过(1),未通过(2),未申请(3)",required = true)
    })
    @Transactional
    public ResponseResult batchUpdate(String[] ids, CheckStatus status, String remark) {
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", ids);
        List<JmRealnameAuthentication> list = service.list(wrapper);
        List<JmRealnameAuthenticationLog> logs = new ArrayList<>();

        if (list.size() == 0) return ResponseResult.error("未查询到相关记录！");
        final JmRealnameAuthentication ja = list.get(0);

        for (int i = 0; i < list.size(); i++) {
            if (ja.getStatus() != list.get(i).getStatus()) {
                return ResponseResult.error("所选记录存在不同审核阶段，请检查！");
            }
        }

        ja.setRemark(remark);
        CheckStatus checkStatus = ja.getStatus();

        if (checkStatus.equals(CheckStatus.未通过)) {
            return ResponseResult.error("未通过记录，不允许操作!");
        }
        ja.setStatus(status);
        list.stream().forEach(i -> {
            i.setRemark(ja.getRemark());
            i.setStatus(ja.getStatus());
            i.setExamineTime(LocalDateTime.now());
            i.setUpdateTime(LocalDateTime.now());
            i.setAdminId(adminId);
            i.setAdminName(adminName);
            JmRealnameAuthenticationLog log = new JmRealnameAuthenticationLog();
            BeanUtils.copyProperties(i, log);
            logs.add(log);
        });
        logService.saveBatch(logs);
        return ResponseResult.success(service.updateBatchById(list));
    }



    @PostMapping("/updateDetail")
    @ApiOperation("更新认证信息")
    @Transactional
    public ResponseResult updateDetail(@Validated RealNameUpdateRequest request, Integer uid) {
        JmUser byId = userService.getById(uid);//查询当前登录人信息
        /**
         * 如果没有当前登录人信息，返回错误。
         */

        if (ObjectUtil.isNotEmpty(byId)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("uid", uid);
            JmRealnameAuthentication realName = realNameService.getOne(wrapper);
            /**
             * 只允许已通过的进行编辑。
             *
             */
            LocalDateTime now = LocalDateTime.now();
            if (ObjectUtil.isNotEmpty(realName) && realName.getStatus().equals(CheckStatus.已通过)) {
                if(StringUtils.isNotBlank(request.getIdcard())){
                    wrapper=new QueryWrapper();
                    wrapper.eq("idcard",request.getIdcard());
                    JmRealnameAuthentication idCardObj = realNameService.getOne(wrapper);
                    if(ObjectUtil.isNotEmpty(idCardObj)&&idCardObj.getUid()!=uid){
                        return ResponseResult.error("身份证号已存在!");
                    }
                }
                realName.setUpdateTime(now);
                BeanUtils.copyProperties(request, realName);
                realName.setAdminId(ServletUtils.getLoginId());
                realName.setAdminName(ServletUtils.getLoginName());
                realNameService.updateById(realName);
            }
            return ResponseResult.success();
        }
        return ResponseResult.error("未查询到用户信息!");

    }
}
